import { uploadFile } from "@/services/file";
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from "react";
import ReactQuill from "react-quill-new";
import "react-quill-new/dist/quill.snow.css";
import styles from "./index.modules.less";

// 注册模块
// 注册模块

type Props = {
  onChange?: (value: string) => void;
  defaultValue?: string;
  placeholder?: string;
  onReady?: (setData: (data: string) => void) => void;
};
export type MyQuillEditorRef = {
  setData: (value: string) => void;
  getData: () => string;
  setReadOnly: (readOnly: boolean) => void;
};
const MyQuillEditor = forwardRef<MyQuillEditorRef, Props>((props, ref) => {
  const { onChange, defaultValue, placeholder } = props;
  const [value, setValue] = useState(defaultValue || "");
  const [readOnly, setReadOnly] = useState(false);
  const quillRef = useRef<any>(null);
  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    setReadOnly,
    setData: (data: string) => setValue(data),
    getData: () => value,
  }));

  useEffect(() => {}, [value]);

  useEffect(() => {
    if (onChange) {
      onChange(value);
    }
  }, [value]);
  // 上传图片的自定义函数
  const handleImageUpload = async () => {
    const input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*");
    input.click();

    input.onchange = async () => {
      const file = input.files?.[0];
      if (!file) return;

      // ✅ Step 1: 上传到你的后端
      const formData = new FormData();
      formData.append("name", "file");
      formData.append("file", file);

      try {
        // 这里替换成你的上传接口
        const { data } = await uploadFile(formData);
        // const data = await res.json();
        console.log("上传成功:", data);
        const imageUrl = data.filePath; // 服务端返回图片访问地址
        const editor = quillRef.current?.getEditor();

        // ✅ Step 2: 插入图片
        const range = editor.getSelection(true);
        editor.insertEmbed(range.index, "image", imageUrl);
      } catch (err) {
        console.error("上传失败:", err);
      }
    };
  };

  // 配置工具栏
  const modules = useMemo(
    () => ({
      toolbar: {
        container: [
          [{ header: [1, 2, false] }],
          ["bold", "italic", "underline", "strike"],
          [{ color: [] }, { background: [] }],
          [{ list: "ordered" }, { list: "bullet" }],
          ["link", "image"],
          ["clean"],
        ],
        handlers: {
          image: handleImageUpload, // 重写 image 按钮行为
        },
      },
    }),
    []
  );

  return (
    <div
      style={{
        height: 245,
      }}
    >
      <ReactQuill
        className={[styles.editor, readOnly ? styles.disabled : ""].join(" ")}
        ref={quillRef}
        theme="snow"
        value={value}
        readOnly={readOnly}
        onChange={setValue}
        modules={modules}
        placeholder={placeholder || "请输入内容..."}
        style={{
          height: 200,
        }}
      />
    </div>
  );
});

export default MyQuillEditor;
